import { error, instantiate, _decorator } from 'cc';
import { VM } from './ViewModel';
import VMBase from './VMBase';

const { ccclass, property, menu, help } = _decorator;
@ccclass
@menu('ModelViewer/VM-StateChilds (VM状态控制)')
export default class VMStateChilds extends VMBase {
    @property
    watchPath: string = "";

    @property(Node)
    copyNode:Node = null;

    @property(Node)
    parentGroup:Node = null;

    @property(Number)
    childsMaxCount:number = -1;


    onLoad(){
        ( this.copyNode as any).active = false;
        super.onLoad();
    }

    //当值初始化时
    protected onValueInit() {
        let value = VM.getValue(this.watchPath);
        (this.parentGroup as any).removeAllChildren();
        let i = 1;
        for (const vo of value) {
            this.addOne(vo);
            if(this.childsMaxCount != -1 && i >= this.childsMaxCount)
            break;
            i++;
        }
        ( this.copyNode as any).active = false;
    }

    //当值被改变时
    protected onValueChanged(newVar: any[], oldVar: any[], pathArr: any[]) {
        if(this.childsMaxCount != -1 && (this.parentGroup as any).childrenCount >= this.childsMaxCount)return;
        let newMap = {};
        let oldMap = {};
        for (const vo of newVar) {
            newMap[vo.key] = vo;
        }
        for (const vo of oldVar) {
            oldMap[vo.key] = vo;
        }

        for (const key in newMap) {
            if(!oldMap[key])
            {
                this.addOne(newMap[key]);
            }
        }

        for (const key in oldMap) {
            if(!newMap[key])
            {
                var data = oldMap[key];
                var node = (this.parentGroup as any).getChildByName(data.key);
                if(node)
                {
                    node.destroy();
                }
                else
                {
                    error("VMStateChilds不存在"+data.key);
                }
            }
        }
    }
    private addOne(vo:any){
        let node:any = instantiate(this.copyNode);
        node.name = vo.key+"";
        node.parent = this.parentGroup;
        node.active = true;
    }
}